﻿//https://leetcode.cn/problems/word-search/?envType=study-plan-v2&envId=top-100-liked

class Solution {
    bool vist[7][7];
    int dx[4] = { 0,0,1,-1 };
    int dy[4] = { 1,-1,0,0 };
    int n, m;
public:
    bool exist(vector<vector<char>>& board, string word)
    {
        n = board.size();
        m = board[0].size();

        for (int i = 0; i < n; i++)
        {
            for (int j = 0; j < m; j++)
            {
                if (board[i][j] == word[0])
                {
                    vist[i][j] = true;
                    if (dfs(board, i, j, 0, word))
                        return true;
                }
            }
        }
        return false;
    }

    bool dfs(vector<vector<char>>& board, int i, int j, int pos, string& word)
    {

        if (pos == word.size() - 1)
        {
            return true;
        }

        for (int k = 0; k < 4; k++)
        {
            int a = i + dx[k], b = j + dy[k];
            if (a >= 0 && a < n && b >= 0 && b < m && !vist[a][b] && board[a][b] == word[pos + 1])
            {
                vist[a][b] = true;
                if (dfs(board, a, b, pos + 1, word)) return true;
            }
        }
        vist[i][j] = false;
        return false;
    }
};